﻿using DataManage;
using ServiceLayerManagement;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace BMSPlatform.DeviceCommunication
{
    public class Command
    {
        /// <summary>
        /// 发送的指令包
        /// </summary>
        public byte[] Data;
        /// <summary>
        /// 所需回包数
        /// </summary>
        public int Length;
        /// <summary>
        /// 指令描述
        /// </summary>
        public string Describe;
        /// <summary>
        /// 应答验证包
        /// </summary>
        public byte[] VerData;

        #region 消息体委托
        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate void MessageTransferEventHandler(string strMessageInfo);
        public MessageTransferEventHandler OnMessageTransEvent;//方法调用
        public event MessageTransferEventHandler MessageTrans//委托方法绑定
        {
            add { OnMessageTransEvent += new MessageTransferEventHandler(value); }
            remove { OnMessageTransEvent -= new MessageTransferEventHandler(value); }
        }
        #endregion

        #region 进度条委托
        [UnmanagedFunctionPointer(CallingConvention.StdCall)]
        public delegate void ProcessBarEventHandler(double currentValue);
        public ProcessBarEventHandler OnProcessBarEventEvent;//方法调用
        public event ProcessBarEventHandler ProcessBarEvent//委托方法绑定
        {
            add { OnProcessBarEventEvent += new ProcessBarEventHandler(value); }
            remove { OnProcessBarEventEvent -= new ProcessBarEventHandler(value); }
        }
        #endregion

        /// <summary>
        /// 补齐数组为指定长度
        /// </summary>
        public byte[] CompleteArray(byte[] currentData, int len)
        {
            List<byte> data = new List<byte>();
            data.AddRange(currentData);
            int count = len - currentData.Length;
            for(int i = 0; i < count; i++)
            {
                data.Add(0x00);
            }
            return data.ToArray();
        }

        /// <summary>
        /// 组装上位机发送指令的帧ID
        /// </summary>
        /// <param name="lowerCId">下位机地址</param>
        /// <param name="sourceBytes">上位机源帧ID</param>
        public uint AssemblyUpperCId(byte lowerCId, List<byte> sourceBytes)
        {
            string str = "";
            sourceBytes.Insert(sourceBytes.Count - 1, lowerCId);
            foreach(byte b in sourceBytes)
            {
                str += $"{b.ToString("X2")}";
            }
            return str.ToUint(System.Globalization.NumberStyles.HexNumber);
        }
    }
}
